//
//  SMSVerificationView.swift
//  ANOA
//
//  Created by zwb on 2017/1/12.
//  Copyright © 2017年 zwb. All rights reserved.
//

import UIKit

// 去短信验证   sms_type  1 原来的   2  薪资查询  force 强制绑定，否则退出
func go2SmsVeri(sms_type:String,force:Bool = false,vc:UIViewController? = nil,passClo:(()->())?) {
 
    let viewController = Bundle.main.loadNibNamed("SMSVerificationView", owner: nil, options: nil)?.last as! SMSVerificationView
    
    viewController.force = force
    viewController.vc = vc
    viewController.sms_type = sms_type
    viewController.verificationPass = {
        if let clo = passClo {
            clo()
        }
    }
    viewController.show()
}


class SMSVerificationView: UIViewController {
    
    @IBOutlet weak var baseView: UIView!
    @IBOutlet weak var phoneNumber: UITextField!
    @IBOutlet weak var verificationNumber: UITextField!
    @IBOutlet weak var sendButton: UIButton!
    @IBOutlet weak var saveButton: UIButton!
    
    weak var vc:UIViewController?
    var force:Bool = false // 强制绑定，否则退出
    // 短信验证通过回调
    var verificationPass: (() -> Void)?
    
    fileprivate var selfReference: SMSVerificationView?
    
    var remainingSeconds = 0 {
        willSet {
            sendButton.setTitle("\(newValue)秒后重新获取", for: UIControl.State())
            sendButton.setTitleColor(UIColor.lightGray, for: UIControl.State())
            sendButton.isEnabled = false
            if newValue <= 0 {
                sendButton.setTitle("获取验证码", for: UIControl.State())
                sendButton.setTitleColor(Theme.LIGHT_BLUE, for: UIControl.State())
                sendButton.isEnabled = true

            }
        }
    }
    var sms_type = "1"
    var countdownTimer: Timer?
    
    var isCounting = false {
        willSet {
            if newValue {
                countdownTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateTime), userInfo: nil, repeats: true)
                remainingSeconds = 60
            } else {
                countdownTimer?.invalidate()
                countdownTimer = nil
            }
            
            sendButton.isEnabled = !newValue
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        phoneNumber.text = USERINFO.tel.unwrap
        phoneNumber.isUserInteractionEnabled = false
        
        sendButton.setTitle("获取验证码", for: UIControl.State())
        sendButton.setTitleColor(Theme.LIGHT_BLUE, for: UIControl.State())
        sendButton.layer.borderWidth = 1
        sendButton.layer.borderColor = Theme.LIGHT_BLUE.cgColor
        sendButton.addTarget(self, action: #selector(sendButtonClick), for: .touchUpInside)
        
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(tapped(_:)))
        tapGesture.numberOfTapsRequired = 1
        view.addGestureRecognizer(tapGesture)
    }
    
    @objc func tapped(_ gestureRecognizer: UITapGestureRecognizer) {
        self.view.endEditing(true)
    }
    
    @IBAction func clickCancalButton(_ sender: UIButton) {
        hideView()
        if force {
            vc?.navigationController?.popViewController(animated: true)
        }
    }
    
    @IBAction func clickVerificationButton(_ sender: UIButton) {
        let idfa = fetchDeciveIdentifier()
        guard let number = phoneNumber.text, number != "" else {
            KSToast("输入手机号码")
            return
        }
        
        let phoneNo = String(number[..<number.index(number.startIndex, offsetBy: 11)])
        
        guard phoneNo.validatePhonenumber() else {
            KSToast("请输入正确格式的手机号")
            return
        }
        
        guard verificationNumber.text != "" else {
            KSToast("输入验证码")
            return
        }
        
        
        KSNetwork.shared.doRequest(API.global(.verificationSms(code: verificationNumber.text.unwrap, identification: idfa,sms_type:"1"))) { (data:BaseResult<OperateResult>) in
            if data.flag == TRUE {
                KSToast("验证成功")
                UserDefaults.standard.set(Date.today, forKey: "\(USERINFO.staffId!)isSmsValid")
                self.hideView()

                if let verificationPass = self.verificationPass {
                    verificationPass()
                }
            } else {
                KSToast(data.errorCombine.unwrap)
            }
        }
        
 
        
    }
    
    @objc fileprivate func sendButtonClick() {
        let idfa = fetchDeciveIdentifier(force: true)
        guard idfa != "" else {
             return
        }
        guard let number = phoneNumber.text, number != "" else {
            KSToast("输入手机号码")
            return
        }
        
        let whiteSpace = CharacterSet.whitespacesAndNewlines
        let num = number.trimmingCharacters(in: whiteSpace)
        
        guard num.count >= 11 else {
            KSToast("手机号码格式错误")
            return
        }
        
        let phoneNo = String(num[..<number.index(number.startIndex, offsetBy: 11)])
        
        isCounting = true
        phoneNumber.isEnabled = false
        
        KSToast("发送验证码")
        KSNetwork.shared.doRequest(API.global(.sendSms(phone: phoneNo, identification: idfa,sms_type:"1"))) { (data:BaseResult<OperateResult>) in
            if data.flag == TRUE {
                KSLog("验证码获取成功")
            } else {
                KSToast(data.errorCombine.unwrap)
            }
            self.phoneNumber.isEnabled = true
        }
 
        
    }
    
    @objc func updateTime(_ timer: Timer) {
        // 计时开始时，逐秒减少remainingSeconds的值
        remainingSeconds -= 1
    }
    
    func show() {
        
        selfReference = self
        view.alpha = 0
        
        let rv = UIApplication.shared.keyWindow! as UIWindow
        rv.addSubview(view)
        view.frame = rv.bounds
        baseView.frame = rv.bounds
        showAnimation()
    }
    
    // Show animation in the alert view
    fileprivate func showAnimation(_ animationStyle: KSAnimationStyle = .topToBottom, animationStartOffset: CGFloat = -400.0, boundingAnimationOffset: CGFloat = 15.0, animationDuration: TimeInterval = 0.2) {
        
        let rv = UIApplication.shared.keyWindow! as UIWindow
        var animationStartOrigin = baseView.frame.origin
        var animationCenter = rv.center
        
        switch animationStyle {
        case .noAnimation:
            view.alpha = 1.0
            return
            
        case .topToBottom:
            animationStartOrigin = CGPoint(x: animationStartOrigin.x, y: baseView.frame.origin.y + animationStartOffset)
            animationCenter = CGPoint(x: animationCenter.x, y: animationCenter.y + boundingAnimationOffset)
            
        case .bottomToTop:
            animationStartOrigin = CGPoint(x: animationStartOrigin.x, y: baseView.frame.origin.y - animationStartOffset)
            animationCenter = CGPoint(x: animationCenter.x, y: animationCenter.y - boundingAnimationOffset)
            
        case .leftToRight:
            animationStartOrigin = CGPoint(x: baseView.frame.origin.x + animationStartOffset, y: animationStartOrigin.y)
            animationCenter = CGPoint(x: animationCenter.x + boundingAnimationOffset, y: animationCenter.y)
            
        case .rightToLeft:
            animationStartOrigin = CGPoint(x: baseView.frame.origin.x - animationStartOffset, y: animationStartOrigin.y)
            animationCenter = CGPoint(x: animationCenter.x - boundingAnimationOffset, y: animationCenter.y)
        }
        
        baseView.frame.origin = animationStartOrigin
        UIView.animate(withDuration: animationDuration, animations: {
            self.view.alpha = 1.0
            self.baseView.center = animationCenter
        }, completion: { _ in
            UIView.animate(withDuration: animationDuration, animations: {
                self.view.alpha = 1.0
                self.baseView.center = rv.center
            })
        })
    }
    
    func hideView() {
        
        
        
        UIView.animate(withDuration: 0.2, animations: {
            self.view.alpha = 0
        }, completion: { _ in
            self.view.removeFromSuperview()
            self.selfReference = nil
        })
    }
}
